package com.greate.community.service;

import com.greate.community.dao.ExpMapper;
import com.greate.community.entity.Exp;
import com.greate.community.entity.User;
import com.greate.community.constant.ExpType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 类名称：ExpService
 * 类描述：经验服务类
 * 创建人：CSUpipixia
 * 创建时间：2022/2/10 21:31
 *
 * @version v1.0
 */
@Slf4j
@Service
public class ExpService {

    @Autowired
    private ExpMapper expMapper;

    @Autowired
    private UserService userService;

    private final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 处理获取经验的事件
     * @param userId
     * @param type
     */
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    public void handleGetExp(int userId, String type) {
        int expCount = 0;

        // 未实名无法获得经验值
        User user = userService.findUserById(userId);
        if (user == null || user.getAuditStatus() != 2) {
            return;
        }
        // 经验值不符合类型
        ExpType expType = ExpType.resolve(type);
        if (expType == null) {
            return;
        }

        Calendar calendar = Calendar.getInstance();
        Date today = calendar.getTime();
        String start = formatter.format(today);
        calendar.add(Calendar.DATE, 1); // 加一天
        String end = formatter.format(calendar.getTime());
        // 判断是否达到上限
        if (expMapper.searchExpsByUserIdAndTypeAndDate(userId, expType.getName(), start, end, 0, 100)
                .stream().mapToInt(Exp::getCount).sum()
                < expType.getLimit()) {
            expCount = expType.getCount();
        }

        addExp(userId, expCount, type);
    }

    public int addExp(int userId, int expCount, String type) {
        int result = 0;
        // 得到了经验值，记录本次经验值，并更新用户exp和rank
        if (expCount > 0) {
            User user = userService.findUserById(userId);
            // 记录本次经验值
            Exp exp = new Exp();
            exp.setCount(expCount);
            exp.setType(type);
            exp.setUserId(userId);
            exp.setCreateTime(new Date());
            int rows = expMapper.insertExp(exp);

            // 更新用户exp和rank
            if (rows == 1) {
                int newExp = user.getExp() + expCount;
                int newLevel = ExpType.getLevel(newExp);
                result = userService.updateExpAndLevel(userId, newExp, newLevel);
            }
        }
        return result;
    }

    public List<Exp> getExpPageByUserId(int userId, int offset, int limit) {
        return expMapper.searchExpByUserId(userId, offset, limit);
    }

}
